﻿using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

namespace nMongo
{
    public partial class MongoEngine
    {
        #region Constructors (2 overloads)
        public MongoEngine() 
            : this(options: MongoEngineOptions.Default)
        {
        }

        public MongoEngine(MongoEngineOptions options)
        {
            this.Options = options;
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings
                .OfType<ConnectionStringSettings>()
                .Where(x => x.ProviderName.Equals("nMongo") || x.Name != string.Empty)
                .FirstOrDefault();

            if (settings == null)
            {
                throw new MongoConnectionException("No ConnectionString key was found using the ConfigurationManager.");
            }

            _BuildConnectionString(settings.ConnectionString);
        }

        public MongoEngine(string connectionString) 
            : this(connectionString, options: MongoEngineOptions.Default)
        {
        }

        public MongoEngine(string connectionString, MongoEngineOptions options)
        {
            this.Options = options;
            _BuildConnectionString(connectionString);
        } 
        #endregion

        protected void _BuildConnectionString(string connectionString)
        {
            MongoUrlBuilder builder = new MongoUrlBuilder(connectionString);

            if (string.IsNullOrEmpty(builder.DatabaseName.Trim()))
            {
                throw new MongoConnectionException("The database name was not found in the connection string specified.");
            }

            this._server = new MongoClient(connectionString).GetServer();
            this.Database = this._server.GetDatabase(builder.DatabaseName);
            this._connectionString = connectionString;
            this._builder = builder;
        }
    }
}
